package com.demo.modules.sys.controller;

import com.demo.common.base.R;
import com.demo.common.exception.RRException;
import com.demo.common.utils.PageUtils;
import com.demo.modules.sys.entity.SysDictEntity;
import com.demo.modules.sys.entity.SysDictValEntity;
import com.demo.modules.sys.form.SysDictQueryForm;
import com.demo.modules.sys.form.SysDictValQueryForm;
import com.demo.modules.sys.service.SysDictService;
import com.demo.modules.sys.service.SysDictValService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 数据字典
 *
 * @author Zsx
 * @date 2019-07-09 19:07:15
 */
@RestController
@RequestMapping("sys/dict")
public class SysDictController {

    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private SysDictValService sysDictValService;


    /**
     * 分页列表
     */
    @GetMapping("/page")
    public R<PageUtils<SysDictEntity>> page(SysDictQueryForm params) {
        PageUtils<SysDictEntity> page = sysDictService.queryPage(params);

        return R.ok(page);
    }

    /**
     * 无分页列表
     */
    @GetMapping("/list")
    public R<List<SysDictEntity>> list(SysDictQueryForm params) {
        List<SysDictEntity> list = sysDictService.queryList(params);

        return R.ok(list);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    public R<SysDictEntity> info(@PathVariable("id") Long id) {
        SysDictEntity sysDict = sysDictService.getById(id);

        return R.ok(sysDict);
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    @RequiresPermissions("sys:dict:save")
    public R save(@RequestBody SysDictEntity sysDict) {
        sysDictService.save(sysDict);

        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @RequiresPermissions("sys:dict:update")
    public R update(@RequestBody SysDictEntity sysDict) {
        sysDictService.updateById(sysDict);

        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @RequiresPermissions("sys:dict:delete")
    public R delete(@RequestBody Long[] ids) {
        SysDictValQueryForm params = new SysDictValQueryForm();
        params.setDictId(ids[0]);
        List<SysDictValEntity> sysDictValEntities = sysDictValService.queryList(params);
        if (sysDictValEntities.size() == 0) {
            sysDictService.removeByIds(Arrays.asList(ids));
        } else {
            throw new RRException("存在字典值,无法删除");
        }
        return R.ok();
    }

}
